package routes

import (
	"gLottery/common"
	"gLottery/internal/application/dto"
	"gLottery/internal/application/service"
	"gLottery/internal/interfaces/middleware"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

var dataStruct map[string]interface{}

type UserRequest struct {
	Email    string `json:"email" binding:"required"`
	Password string `json:"password" binding:"required"`
	Username string `json:"username"`
	Token 	string `json:"token"`
}

func RegisterUserRoutes(r *gin.Engine, userService *service.UserService, auth *middleware.Auth) {
	userGroup := r.Group("/api/users")
	{
		userGroup.POST("/register", func(c *gin.Context) {
			var req dto.RegisterRequest
			if err := c.ShouldBindJSON(&req); err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
				return
			}

			user := &dto.RegisterRequest{
				Username: req.Username,
				Email:    req.Email,
				Password: req.Password,
			}

			if err := userService.Register(user); err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
				return
			}

			c.JSON(http.StatusCreated, gin.H{"message": "User created"})
		})

		userGroup.POST("/login", func(c *gin.Context) {
			var req UserRequest
			if err := c.ShouldBindJSON(&req); err != nil {
				// 400 参数校验失败
				common.ResponseErrorWithMsg(c,http.StatusBadRequest,err.Error())
				return
			}
			token, err := userService.Login(req.Email, req.Password)
			if err != nil {
				common.ResponseErrorWithMsg(c,http.StatusUnauthorized,err.Error())
				return
			}
			// 3.返回响应
			common.ResponseTokenSuccess(c, token)
		})
		//需要放入jwt
		userGroup.Use(auth.Validate())
		userGroup.GET("/profile", func(c *gin.Context) {
			userID, _ := c.Get("userID")
			zap.L().Info("你好")
			user, err := userService.GetProfile(c.Request.Context(),userID.(uint))
			if err != nil {
				common.ResponseErrorWithMsg(c,http.StatusNotFound,"not found")
				return
			}

			c.JSON(http.StatusOK, gin.H{
				"id":       user.ID,
				"username": user.Username,
				"email":    user.Email,
			})
		})
	}
}